package com.feng.controller;

import com.feng.Exception.SystemException;
import com.feng.domain.ResponseResult;
import com.feng.domain.dto.UserSaveDto;
import com.feng.domain.entity.User;
import com.feng.domain.enums.AppHttpCodeEnum;
import com.feng.domain.vo.UserUpdateVo;
import com.feng.service.UserService;
import com.feng.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/system/user")
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/list")
    public ResponseResult list(User user, Integer pageNum, Integer pageSize) {
        return userService.selectUserPage(user,pageNum,pageSize);
    }
    @PostMapping
    public ResponseResult addUser(@RequestBody UserSaveDto userSaveDto){
         //用户名不能为空
        if(!StringUtils.hasText(userSaveDto.getUserName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        //密码不能为空
        if(!StringUtils.hasText(userSaveDto.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        //邮箱不能为空
        if(!StringUtils.hasText(userSaveDto.getEmail())){
            throw new SystemException(AppHttpCodeEnum.PHONE_NOT_NULL);
        }
        //用户名不能重复
        if (userService.checkUserNameUnique(userSaveDto.getUserName())==false){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        //手机号不能重复
        if (userService.checkPhoneUnique(userSaveDto.getPhonenumber())==false){
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }
        //邮箱不能重复
        if (userService.checkEmailUnique(userSaveDto.getEmail())==false){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        return userService.addUser(userSaveDto);
    }
    /**
     * 删除用户
     */
    @DeleteMapping("/{userIds}")
    public ResponseResult remove(@PathVariable List<Long> userIds) {
        if(userIds.contains(SecurityUtils.getUserId())){
            return ResponseResult.errorResult(500,"不能删除当前你正在使用的用户");
        }
        userService.removeByIds(userIds);
        return ResponseResult.okResult();
    }
    @GetMapping("/{id}")
    public ResponseResult getDetailByUserId(@PathVariable Long id){
        return userService.getDetailByUserId(id);
    }
    @PutMapping
    public ResponseResult updateUser(@RequestBody UserUpdateVo userUpdateVo){
        return userService.updateUser(userUpdateVo);
    }
}
